require 'digest'
class PhotosController < ApplicationController
  before_filter :require_admin,           :except => [:show]
  before_filter :find_photo,              :except => [:index, :new, :create, :update_many]
  before_filter :find_list_items
  before_filter :check_photo_privacy,     :only => [:show]
  
  def index
    @photos = Photo.find(:all, :conditions => ['parent_id IS ?', nil], :order => 'created_at desc').paginate :page => params[:page], :per_page => 24, :order => 'created_at'
    respond_to do |format|
      format.html {}
      format.js   { 
        @gallery = Gallery.find(params[:gallery_id]) 
        render :partial => 'galleries/photos', :locals =>{:gallery => @gallery}
      }
    end
  end
  
  def show 
    @comment  = Comment.new
    @item     = Item.new
  end
  
  def new
    @photo = Photo.new
  end
  
  def create
    params[:photo_attributes] ||= {}
    if File.extname(params[:photos].first.original_filename).downcase == ".zip"
      Zip::ZipFile.foreach(params[:photos].first.path) do |zip_entry|
        if zip_entry.file? and !zip_entry.to_s.match(/^__MACOSX.*$/) and ((File.extname(zip_entry.to_s).downcase == ".jpeg") or (File.extname(zip_entry.to_s).downcase == ".jpg"))
          ActionController::UploadedTempfile.open(rand(1<<60).to_s) do |temp|
            zip_entry.extract(temp.path){true}
            temp.original_path = zip_entry.to_s
            temp.content_type = 'image/jpeg'
            Photo.create!({:uploaded_data => temp}.merge(params[:photo_attributes]))
          end
        end
      end
      flash[:update] = 'The zip file has been uploaded and the images in it have been added to the database.'
    else
      params[:photos].each {|photo| (@photo = Photo.create!({:uploaded_data => photo}.merge(params[:photo_attributes]))) unless photo == ""}
      flash[:update] = "The photo <a href=\"#{photo_url(@photo)}\">#{@photo.filename}</a> has been uploaded."
    end
    redirect_to new_photo_url
  rescue ActiveRecord::ActiveRecordError
    flash[:error] = 'Errors were detected, see below.'  
    render :action => 'new'
  end
  
  def edit
  end
  
  def update
    params[:photo][:random] ||= []
    params[:photo][:is_private] ||= []
    params[:photo][:gallery_ids] ||= []
    params[:photo][:is_thumbnail] ||= []
    params[:photo][:non_purchasable] ||= []
    @photo.update_attributes!(params[:photo])
    flash[:update] = 'Information for this photo has been updated.'
    redirect_to photo_url(@photo)
  rescue ActiveRecord::RecordInvalid
    flash[:error] = 'Errors were detected, see below.'
    render :action => 'edit'
  end
  
  def update_many
    if params[:photo_ids]
      params[:photo_ids].each {|photo_id| Photo.find(photo_id).update_attributes!(params[:photo])} unless params[:delete]
      params[:photo_ids].each {|photo_id| Photo.find(photo_id, :include => :galleries).galleries << Gallery.find(params[:gallery_id])} unless params[:delete] or params[:gallery_id].blank?
      params[:photo_ids].each {|photo_id| Photo.find(photo_id).destroy} if params[:delete]
      flash[:update] = 'The photos have been updated' unless params[:delete]
      flash[:update] = 'The photos have been deleted' if params[:delete]
    end
    redirect_to :action => :index
  end
  
  def destroy
    @photo.destroy
    flash[:update] = 'The photo has been deleted.'
    redirect_to photos_url
  end
  
protected
  def check_photo_privacy
    if logged_in? and @photo.is_private?
      unless current_user.authorized_to_view?(@photo)
        flash[:error] = "Sorry, but you're not authorized to view that photo"
        redirect_back_or_default('/')
      end
    elsif @photo.is_private?
      flash[:error] = "Sorry, but you're not authorized to view that photo"
      redirect_back_or_default('/')
    end
  end
  def require_login
    unless logged_in?
      flash[:error] = 'You must be logged in to do that'
      redirect_to login_url
    end
  end
  def require_admin
    if logged_in?
      unless current_user.is_admin?
        flash[:error] = "Must be an administrator to do that, sorry."
        redirect_back_or_default('/')
      end
    else
      flash[:error] = 'You must be logged in to do that'
      redirect_to login_url
    end
  end
  def find_photo
    @photo = Photo.find params[:id]
  end
  def find_list_items
    @users = User.find(:all, :conditions => ['is_client = ?', true], :order => 'login desc')
    @galleries = Gallery.find(:all, :order => 'created_at desc')
    @photo_sizes = PhotoSize.find(:all)
  end
end